package lottery;

import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;

/**
 * Created by huanggc on 2019/10/28.
 */
public class Lottery {

    static java.util.List<String> users = new ArrayList<>();
    static Random r = new Random();
    static boolean flag = true;

    public static void main(String[] args) throws  Exception{
        initData();
        System.out.println("学生信息初始化成功============学生人数为：" + users.size());
        JFrame frame = new JFrame("惊喜大抽奖");
        frame.setBounds(500, 300, 400, 350);

        JPanel mainPanel = new JPanel();
        frame.setContentPane(mainPanel);

        JPanel accountPanel = new JPanel();
        accountPanel.setBounds(100, 110, 200, 50);
        JTextField tf = new JTextField();
        Font font = new Font("黑体", Font.PLAIN, 20);
        tf.setColumns(10);
        tf.setFont(font);
        accountPanel.add(tf);
        JButton btn = new JButton("开始");

        Timer timer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tf.setText(users.get(r.nextInt(users.size())));
            }
        });

        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = btn.getText();
                if(text.equals("开始")){
                    flag = true;
                    btn.setText("结束");
                    new Thread(){
                        @Override
                        public void run() {
                            while (flag){
                                tf.setText(users.get(r.nextInt(users.size())));
                            }
                        }
                    }.start();
                    //timer.start();
                }else{
                    //timer.stop();
                    btn.setText("开始");
                    flag = false;
                }
            }
        });
        accountPanel.add(btn);
        mainPanel.add(accountPanel);

        frame.setLayout(null);//不使用系统布局方式
        //frame.setLayout(new FlowLayout());//流式布局
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗体退出程序
        frame.setVisible(true);
    }

    private static void initData() throws  Exception{
        File file = new File("C:\\Users\\huanggc\\Desktop\\课堂积分\\1.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String str = "";
        while((str = br.readLine()) != null){
            users.add(str.split("\\#")[0]);
        }
        br.close();
    }
}
